"use client"

import { useState, useEffect, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  ArrowLeft,
  TrendingUp,
  TrendingDown,
  Activity,
  Target,
  BarChart3,
  Filter,
} from "lucide-react"
import { 
  getSignalTrades,
  SignalTradeDetail,
  GetSignalTradesParams,
  convertTradeData
} from "@/lib/api/tracking"
import { useToast } from "@/hooks/use-toast"
import { cn } from "@/lib/utils"
import { ThemeSwitch } from "@/components/theme-switch"
import { UserNav } from "@/components/user-nav"

/**
 * 格式化百分比
 */
const formatPercent = (value: number, showSign = true, decimals = 2) => {
  const sign = showSign && value > 0 ? '+' : ''
  return `${sign}${value.toFixed(decimals)}%`
}

/**
 * 交易明细页面
 */
export default function SignalTradesPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { toast } = useToast()
  const scrollContainerRef = useRef<HTMLDivElement>(null)

  // 从URL获取参数
  const signalName = searchParams.get('signal') || ''
  const startDate = searchParams.get('startDate') || ''
  const endDate = searchParams.get('endDate') || ''

  // 状态
  const [tradeDetails, setTradeDetails] = useState<SignalTradeDetail[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [filterType, setFilterType] = useState<'all' | 'profit' | 'loss'>('all')
  const [sortBy, setSortBy] = useState<'date' | 'return' | 'holding'>('date')
  
  // 分页状态（现在只用于记录总数）
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(0)
  const [totalRecords, setTotalRecords] = useState(0)

  // 加载交易明细 - 一次性加载所有数据
  const loadTrades = async () => {
    if (!signalName) return

    setIsLoading(true)

    try {
      console.log(`🔍 加载所有交易明细...`, { signalName, startDate, endDate })
      
      const params: GetSignalTradesParams = {
        signalName,
        page: 1,
        pageSize: 9999, // 使用一个很大的数字来获取所有数据
      }
      
      if (startDate) params.startDate = startDate
      if (endDate) params.endDate = endDate
      
      const response = await getSignalTrades(params)
      console.log('📊 API返回交易明细:', response)
      
      if (response.data) {
        const { data, total } = response.data
        const convertedData = data.map(convertTradeData)
        
        console.log(`✅ 加载成功，共 ${convertedData.length} 条记录（总计 ${total} 条）`)
        
        setTradeDetails(convertedData)
        setTotalRecords(total)
        setTotalPages(1) // 所有数据都在一页
        setCurrentPage(1)
        
        if (total === 0) {
          toast({
            title: "暂无交易记录",
            description: `信号"${signalName}"在选定时间范围内暂无交易记录`,
            duration: 3000,
          })
        } else {
          toast({
            title: "数据加载成功",
            description: `共加载 ${total} 条交易记录`,
            duration: 2000,
          })
        }
      }
    } catch (error) {
      console.error('❌ 加载交易明细失败:', error)
      toast({
        title: "数据加载失败",
        description: "无法获取交易明细，请检查网络连接",
        variant: "destructive",
        duration: 5000,
      })
    } finally {
      setIsLoading(false)
    }
  }

  // 初始加载
  useEffect(() => {
    if (signalName) {
      loadTrades()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [signalName, startDate, endDate])

  // 计算统计数据
  const stats = {
    total: tradeDetails.length,
    profit: tradeDetails.filter(t => t.isWin).length,
    loss: tradeDetails.filter(t => !t.isWin).length,
    winRate: tradeDetails.length > 0 
      ? (tradeDetails.filter(t => t.isWin).length / tradeDetails.length) * 100 
      : 0,
    avgReturn: tradeDetails.length > 0
      ? tradeDetails.reduce((sum, t) => sum + t.returnRate, 0) / tradeDetails.length
      : 0,
  }

  // 筛选和排序
  const filteredAndSortedTrades = tradeDetails
    .filter(trade => {
      if (filterType === 'all') return true
      if (filterType === 'profit') return trade.isWin
      if (filterType === 'loss') return !trade.isWin
      return true
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'date':
          return new Date(b.buyDate).getTime() - new Date(a.buyDate).getTime()
        case 'return':
          return b.returnRate - a.returnRate
        case 'holding':
          return b.holdingDays - a.holdingDays
        default:
          return 0
      }
    })

  // 如果没有信号名称，显示错误
  if (!signalName) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <Card className="max-w-md">
          <CardContent className="p-6">
            <h2 className="text-xl font-bold mb-2">参数错误</h2>
            <p className="text-muted-foreground mb-4">未指定信号名称</p>
            <Button onClick={() => router.push('/signals')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回信号列表
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="border-b bg-card sticky top-0 z-10">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => router.back()}
              >
                <ArrowLeft className="w-5 h-5" />
              </Button>
              <div>
                <h1 className="text-2xl font-bold flex items-center gap-3">
                  <div className="w-1 h-8 bg-accent rounded-full" />
                  {signalName}
                </h1>
                <p className="text-sm text-muted-foreground mt-1">
                  信号交易明细与绩效分析
                </p>
              </div>
            </div>

            <div className="flex items-center space-x-4">
              {totalRecords > 0 && (
                <Badge variant="outline" className="text-base px-4 py-2 font-mono">
                  共 {totalRecords} 笔交易 (已加载 {stats.total})
                </Badge>
              )}
              <div className="flex items-center space-x-2">
                <ThemeSwitch />
                <UserNav />
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main 
        ref={scrollContainerRef}
        className="container mx-auto px-4 py-6 overflow-y-auto"
        style={{ height: 'calc(100vh - 80px)' }}
      >
        {isLoading ? (
          <div className="space-y-4">
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-24 w-full rounded-lg" />
              ))}
            </div>
            <Skeleton className="h-12 w-full rounded-lg" />
            <div className="space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-16 w-full rounded-lg" />
              ))}
            </div>
          </div>
        ) : (
          <div className="space-y-6">
            {/* 统计卡片 */}
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              {/* 总交易次数 */}
              <Card className="border-l-4 border-l-accent bg-gradient-to-br from-accent/5 to-transparent hover:shadow-lg transition-all duration-300">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs font-medium text-muted-foreground">总交易次数</p>
                    <BarChart3 className="w-4 h-4 text-accent" />
                  </div>
                  <p className="text-2xl font-bold font-mono">{stats.total}</p>
                  <p className="text-xs text-muted-foreground mt-1">笔交易记录</p>
                </CardContent>
              </Card>

              {/* 盈利交易 */}
              <Card className="border-l-4 border-l-success bg-gradient-to-br from-success/5 to-transparent hover:shadow-lg transition-all duration-300">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs font-medium text-muted-foreground">盈利交易</p>
                    <TrendingUp className="w-4 h-4 text-success" />
                  </div>
                  <p className="text-2xl font-bold font-mono text-success">{stats.profit}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    占比 {stats.total > 0 ? ((stats.profit / stats.total) * 100).toFixed(1) : 0}%
                  </p>
                </CardContent>
              </Card>

              {/* 亏损交易 */}
              <Card className="border-l-4 border-l-destructive bg-gradient-to-br from-destructive/5 to-transparent hover:shadow-lg transition-all duration-300">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs font-medium text-muted-foreground">亏损交易</p>
                    <TrendingDown className="w-4 h-4 text-destructive" />
                  </div>
                  <p className="text-2xl font-bold font-mono text-destructive">{stats.loss}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    占比 {stats.total > 0 ? ((stats.loss / stats.total) * 100).toFixed(1) : 0}%
                  </p>
                </CardContent>
              </Card>

              {/* 交易胜率 */}
              <Card className="border-l-4 border-l-primary bg-gradient-to-br from-primary/5 to-transparent hover:shadow-lg transition-all duration-300">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs font-medium text-muted-foreground">交易胜率</p>
                    <Target className="w-4 h-4 text-primary" />
                  </div>
                  <p className="text-2xl font-bold font-mono">{stats.winRate.toFixed(1)}%</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    {stats.profit}胜/{stats.loss}负
                  </p>
                </CardContent>
              </Card>

              {/* 平均收益率 */}
              <Card className="border-l-4 border-l-purple-500 bg-gradient-to-br from-purple-500/5 to-transparent hover:shadow-lg transition-all duration-300">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs font-medium text-muted-foreground">平均收益率</p>
                    <Activity className="w-4 h-4 text-purple-500" />
                  </div>
                  <p className={cn(
                    "text-2xl font-bold font-mono",
                    stats.avgReturn >= 0 ? "text-success" : "text-destructive"
                  )}>
                    {formatPercent(stats.avgReturn)}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">所有交易平均</p>
                </CardContent>
              </Card>
            </div>

            {/* 筛选和排序 */}
            <Card className="bg-muted/30">
              <CardContent className="p-4">
                <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                  <div className="flex items-center gap-2">
                    <Filter className="w-4 h-4 text-muted-foreground" />
                    <span className="text-sm font-medium">数据筛选</span>
                  </div>

                  <div className="flex flex-wrap items-center gap-3">
                    {/* 筛选按钮 */}
                    <div className="flex items-center gap-2">
                      <Button
                        variant={filterType === 'all' ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => setFilterType('all')}
                      >
                        全部 ({stats.total})
                      </Button>
                      <Button
                        variant={filterType === 'profit' ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => setFilterType('profit')}
                      >
                        <TrendingUp className="w-3 h-3 mr-1" />
                        盈利 ({stats.profit})
                      </Button>
                      <Button
                        variant={filterType === 'loss' ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => setFilterType('loss')}
                      >
                        <TrendingDown className="w-3 h-3 mr-1" />
                        亏损 ({stats.loss})
                      </Button>
                    </div>

                    <div className="w-px h-6 bg-border" />

                    {/* 排序选择 */}
                    <Select value={sortBy} onValueChange={(v: any) => setSortBy(v)}>
                      <SelectTrigger className="w-[140px] h-8 text-xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="date">按日期排序</SelectItem>
                        <SelectItem value="return">按收益排序</SelectItem>
                        <SelectItem value="holding">按持仓排序</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 交易明细表格 */}
            <Card>
              <div className="rounded-lg overflow-hidden border">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50 hover:bg-muted/50">
                      <TableHead className="w-16 font-semibold">#</TableHead>
                      <TableHead className="font-semibold">股票信息</TableHead>
                      <TableHead className="font-semibold">信号</TableHead>
                      <TableHead className="font-semibold">买入信息</TableHead>
                      <TableHead className="font-semibold">卖出信息</TableHead>
                      <TableHead className="text-center font-semibold">持仓</TableHead>
                      <TableHead className="text-right font-semibold">收益率</TableHead>
                      <TableHead className="text-center font-semibold">状态</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredAndSortedTrades.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={8} className="text-center py-12 text-muted-foreground">
                          暂无交易记录
                        </TableCell>
                      </TableRow>
                    ) : (
                      filteredAndSortedTrades.map((trade, index) => (
                        <TableRow 
                          key={`${trade.stockCode}-${trade.buyDate}-${index}`}
                          className="hover:bg-accent/5 transition-colors"
                        >
                          <TableCell className="font-medium text-muted-foreground">
                            {index + 1}
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <p className="font-mono text-sm font-semibold">{trade.stockCode}</p>
                              <p className="text-xs text-muted-foreground">{trade.stockName}</p>
                            </div>
                          </TableCell>
                          <TableCell className="max-w-md">
                            <p className="text-xs text-muted-foreground leading-relaxed">
                              {trade.signalDescription}
                            </p>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <p className="text-xs text-muted-foreground">{trade.buyDate}</p>
                              <p className="font-mono text-sm font-medium">¥{trade.buyPrice.toFixed(2)}</p>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              {trade.sellDate === '持仓中' ? (
                                <>
                                  <Badge variant="secondary" className="text-xs">持仓中</Badge>
                                  <p className="font-mono text-xs text-muted-foreground">-</p>
                                </>
                              ) : (
                                <>
                                  <p className="text-xs text-muted-foreground">{trade.sellDate}</p>
                                  <p className="font-mono text-sm font-medium">¥{trade.sellPrice.toFixed(2)}</p>
                                </>
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="text-center">
                            <Badge variant="outline" className="font-mono">
                              {trade.holdingDays}天
                            </Badge>
                          </TableCell>
                          <TableCell className="text-right">
                            <div className="flex flex-col items-end gap-1">
                              <div className="flex items-center gap-2">
                                {trade.isWin ? (
                                  <TrendingUp className="w-4 h-4 text-success" />
                                ) : (
                                  <TrendingDown className="w-4 h-4 text-destructive" />
                                )}
                                <span className={cn(
                                  "font-bold font-mono text-base",
                                  trade.isWin ? "text-success" : "text-destructive"
                                )}>
                                  {formatPercent(trade.returnRate)}
                                  {trade.sellDate === '持仓中' && (
                                    <span className="text-xs ml-1">(浮动收益)</span>
                                  )}
                                </span>
                              </div>
                            </div>
                          </TableCell>
                          <TableCell className="text-center">
                            {trade.sellDate === '持仓中' ? (
                              <Badge className="bg-blue-500/20 text-blue-600 dark:text-blue-400 hover:bg-blue-500/30 border-blue-500/30">
                                ⏱ 持仓中
                              </Badge>
                            ) : trade.isWin ? (
                              <Badge className="bg-success/20 text-success hover:bg-success/30 border-success/30">
                                ✓ 盈利
                              </Badge>
                            ) : (
                              <Badge className="bg-destructive/20 text-destructive hover:bg-destructive/30 border-destructive/30">
                                ✗ 亏损
                              </Badge>
                            )}
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </Card>

            {/* 已加载全部提示 */}
            {stats.total > 0 && (
              <div className="text-center py-4 text-sm text-muted-foreground">
                已加载全部 {totalRecords} 条记录
              </div>
            )}
          </div>
        )}
      </main>
    </div>
  )
}

